import tronUtils from "@TronUtils";
class Trc20Token{
    constructor(_contractAddr) {
        this.hexAddress = tronUtils.addressToHex(_contractAddr);
        this.tronWeb = tronUtils.getTronWeb()
    }

    getContract = function(){
        return this.hexAddress;
    }

    /**
     * 获取余额
     * @param address
     * @return BigNumber
     */
    balanceOf = async function(address){
        let contract = await this.tronWeb.contract().at(this.hexAddress);
        let balance = await contract.balanceOf(address).call();
        return balance
    }

    /**
     * 发起交易
     * @param toAddress
     * @param amount
     * @param remark
     * @return {Promise<void>}
     */
    transfer = async function(fromAddress,privateKey,toAddress,amount,remark){
        const parameter = [{type:'address',value:toAddress},{type:'uint256',value:amount}]
        const transaction = await this.tronWeb.transactionBuilder.triggerSmartContract(this.hexAddress, "transfer(address,uint256)", {},
            parameter,this.tronWeb.address.toHex(fromAddress))
        transaction.transaction.data = remark
        let signedTx  = await this.tronWeb.trx.sign(transaction.transaction,privateKey)
        await this.tronWeb.trx.sendRawTransaction(signedTx);
        return signedTx.txID
    }

    /**
     * 发起交易 这个要是tronWeb中设置私钥
     * @param toAddress
     * @param amount
     * @return {Promise<*>}
     */
    easyTransfer = async function(toAddress,amount){
        let contract = await this.tronWeb.contract().at(this.hexAddress);
        let txid = await contract.transfer(toAddress,amount).send();
        return txid
    }

}

export default Trc20Token;